package com.tanhua.dubbo.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @Author 王加鑫
 * @Date 2021/09/05 22:05
 * @Since JDK 1.8
 * 异步写入数据
 */
@Service
@Slf4j
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 使用异步的方式给不同用户的时间线表写入数据
     */
    @Async //异步执行，原理：底层开一个线程去执行该方法
    public CompletableFuture<String> saveTimeLine(ObjectId publishId,Long userId){
        try {
            Query queryUsers = Query.query(Criteria.where("userId").in(userId));
            List<Users> usersList = this.mongoTemplate.find(queryUsers, Users.class);
            if(CollUtil.isEmpty(usersList)){
                //根据userId查询不到数据
                return CompletableFuture.completedFuture("ok");
            }
            //遍历usersList就为了获取friendId的集合
            for (Users users : usersList) {
                //一切都是为了给TimeLine表写入数据
                TimeLine timeLine = new TimeLine();
                timeLine.setId(ObjectId.get());
                timeLine.setPublishId(publishId);
                timeLine.setDate(System.currentTimeMillis());
                //根据不同的friendId写入到不同好友的时间线表中
                this.mongoTemplate.save(timeLine, "quanzi_time_line_" + users.getFriendId());
            }
        } catch (Exception e) {
            log.error("写入好友时间线表失败 userId=" + userId + ", publishId = " + publishId,e);
            //TODO 出现异常，事务回滚(分布式事务可以处理，单节点无法处理)
            return CompletableFuture.completedFuture("error");
        }
        return CompletableFuture.completedFuture("ok");
    }
}
